"use strict";

const Controller = require("egg").Controller;

class TaskController extends Controller {
  // 添加任务
  async taskAdd() {
    // INSERT INTO task (tname,ttime_start,ttime_end,tstate,ttype,ttotal,ttotal_end,ttotal_unusual) VALUES (tname,ttime_start,ttime_end,tstate,ttype,ttotal,ttotal_end,ttotal_unusual);
    const { ctx } = this;

    let {
      tname,
      ttime_start,
      ttime_end,
      tstate,
      ttype,
      ttotal,
      ttotal_end,
      ttotal_unusual,
      tintroduce,
    } = ctx.request.body;

    // 开始时间
    ttime_start = "DEFAULT";
    ttype = "DEFAULT";
    ttotal_end = "DEFAULT";
    ttotal_unusual = "DEFAULT";

    if (ttime_end == "") ttime_end = null;
    let results = await this.app.mysql.query(
      `INSERT INTO task (tname,ttime_start,ttime_end,tstate,ttype,ttotal,ttotal_end,ttotal_unusual, tintroduce) VALUES 
      ('${tname}',${ttime_start},${ttime_end},${tstate},${ttype},${ttotal},${ttotal_end},${ttotal_unusual}, '${tintroduce}');`
    );

    ctx.body = {
      code: 200,
      data: results,
    };
  }

  // 查询任务列表
  async taskList() {
    const { ctx } = this;
    const { pageNum, pageSize, ttype } = ctx.query;

    // 查询条件
    let where = ``;
    if (ttype) {
      where += `WHERE ttype=${ttype}`;
    }

    let results = await this.app.mysql
      .query(`SELECT * FROM task ${where} ORDER BY ttype, ttime_start DESC
    LIMIT ${(pageNum - 1) * pageSize}, ${pageSize};`);
    let count = await this.app.mysql.query(
      `SELECT count(*) FROM task ${where};`
    );

    ctx.body = {
      code: 200,
      data: { results, pageNum, pageSize, count: count[0]["count(*)"] },
    };
  }

  // 查询任务 一个
  async taskOne() {
    const { ctx } = this;
    const { tid } = ctx.query;

    // 查询条件
    let where = `WHERE tid=${tid}`;

    let results = await this.app.mysql.query(`SELECT * FROM task ${where};`);

    ctx.body = {
      code: 200,
      data: { results },
    };
  }

  // 终止任务
  async taskStop() {
    // INSERT INTO task (tname,ttime_start,ttime_end,tstate,ttype,ttotal,ttotal_end,ttotal_unusual) VALUES (tname,ttime_start,ttime_end,tstate,ttype,ttotal,ttotal_end,ttotal_unusual);
    const { ctx } = this;
    let { ttype, tid } = ctx.request.body;
    let results = await this.app.mysql.query(
      `UPDATE task SET ttype=${ttype} WHERE tid=${tid};`
    );
    ctx.body = {
      code: 200,
      data: results,
    };
  }
}

module.exports = TaskController;
